<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-4
 * Time: 下午6:14
 */

namespace admin\behaviars;


use common\components\tools\ArrayHelper;
use common\models\db\Action;
use common\models\db\Role;
use common\models\db\RoleAction;
use common\models\db\RoleUser;
use common\models\db\User;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;

class Rbac extends AccessControl
{
    /**
     * @param \yii\base\ActionEvent $event
     * @throws ForbiddenHttpException
     */
    public function afterFilter($event)
    {
        parent::afterFilter($event);
        if (!\Yii::$app->user->identity->is_super){
            $actions = Action::find()->alias('action')->select(['action.id', 'action.uri'])
                ->leftJoin(RoleAction::tableName()." as ra", 'action.id = ra.action_id')
                ->leftJoin(Role::tableName()." as role", 'ra.role_id = role.id')
                ->leftJoin(RoleUser::tableName()." as ru", 'role.id = ru.role_id')
                ->leftJoin(User::tableName()." as user", 'ru.user_id = user.id')
                ->where(['user.id' => \Yii::$app->user->id, 'action.yii2_app_id' => \Yii::$app->appinfo->yii2App->id])
                ->asArray()->all();
            $actions = \yii\helpers\ArrayHelper::map($actions, 'id', 'uri');
            $route = $event->action->controller->route;
            $allows = [$route];
            $allows = ArrayHelper::matchDecare($route, $allows);
            $isIn = array_intersect($actions, $allows);
            if (!$isIn){
                throw new ForbiddenHttpException(\Yii::t('yii', 'You are not allowed to perform this action.'));
            }
        }
    }
}